<!--  学生宿舍关系表-->
<template>
  <div>
    <!--    条件查询-->
    <el-form :model="searchForm" class="demo-form-inline">
      <el-row :gutter="20" align="middle">
        <el-col :span="4">
          <el-form-item label="楼栋名称" prop="address">
            <el-select v-model="searchForm.buildingId" placeholder="请选择楼栋" size="medium">
              <el-option v-for="item in buildingName" :key="item.value" :label="item.label"
                         :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="宿舍类型">
            <el-select v-model="searchForm.dormitoryType" placeholder="请选择宿舍类型" size="medium">
              <el-option label="女生宿舍" value="0"></el-option>
              <el-option label="男生宿舍" value="1"></el-option>
              <el-option label="混合宿舍" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="单元名称">
            <el-select v-model="searchForm.unitId" placeholder="请选择单元名称">
              <el-option v-for="item in unitCode" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="层数">
            <el-input v-model="searchForm.floor" placeholder="请输入楼层" size="medium"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="房间号">
            <el-select v-model="searchForm.dormitoryId" placeholder="请选择房间号">
              <el-option v-for="item in roomNumber" :key="item.value" :label="item.label"
                         :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row :gutter="20" align="middle">
        <el-col :span="4">
          <el-form-item label="床位数">
            <el-input v-model="searchForm.dormitoryBed" placeholder="请输入床位数" size="medium"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="学生姓名">
            <el-input v-model="searchForm.name" placeholder="请输入学生姓名" size="medium"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="住宿状态">
            <el-select v-model="searchForm.checkOutOrNot" placeholder="请选择住宿状态" size="medium">
              <el-option label="已退宿" value="是"></el-option>
              <el-option label="未退宿" value="否"></el-option>
              <el-option label="全部" value=""></el-option>
            </el-select>

          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="宿舍状态" prop="status">
            <el-select v-model="searchForm.status" placeholder="请选择宿舍状态" size="medium">
              <el-option label="空闲" value="空闲"></el-option>
              <el-option label="正常" value="正常"></el-option>
              <el-option label="维修中" value="维修中"></el-option>
              <el-option label="暂停使用" value="暂停使用"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item style="margin-top:40px">
            <el-button size="medium" type="primary" @click="fetchData">搜索</el-button>
            <el-button size="medium" type="info" @click="handleReset">清除</el-button>
            <el-button size="medium" type="success" @click="showAddUnitModal">分配宿舍</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!--    添加按钮-->
    <el-dialog
        :visible.sync="isAddDormitoryAllocationVisible"
        title="添加宿舍分配信息"
        width="50%">
      <AddDormitoryAllocation @AddDormitoryAllocation="hideDialog"
                              @submit="handleAddDormitoryAllocation"></AddDormitoryAllocation>
    </el-dialog>

    <!--    <el-dialog-->
    <!--        title="修改宿舍分配信息"-->
    <!--        :visible.sync="isUpdateDormitoryAllocationVisible"-->
    <!--        width="50%">-->
    <!--      <UpdateDormitoryAllocation @submit="handleUpdateDormitoryAllocation" :message="message" @UpdateDormitoryAllocation="hideDialog"></UpdateDormitoryAllocation>-->
    <!--    </el-dialog>-->

    <!--  展示宿舍学生关系表-->
    <el-table :data="dormitoryAllocationList" border stripe>
      <el-table-column v-if="false" align="center" label="分配id" prop="assignmentId"></el-table-column>
      <el-table-column v-if="false" align="center" label="宿舍ID" prop="dormitoryId"></el-table-column>
      <el-table-column align="center" label="楼栋名称" prop="buildingName"></el-table-column>
      <el-table-column align="center" label="宿舍类型" prop="dormitoryType">
        <template slot-scope="scope">
          {{ dormitoryTypeMap[scope.row.dormitoryType] }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="单元名称" prop="unitCode"></el-table-column>
      <el-table-column align="center" label="楼层" prop="floor" width="50vm"></el-table-column>
      <el-table-column align="center" label="房间号" prop="roomNumber" width="63vm"></el-table-column>
      <el-table-column align="center" label="学生" prop="name"></el-table-column>
      <el-table-column align="center" label="床位数" prop="dormitoryBed" width="63vm"></el-table-column>
      <el-table-column align="center" label="已分配" prop="assigned" width="63vm"></el-table-column>
      <el-table-column v-if="false" align="center" label="学生id" prop="userId"></el-table-column>
      <el-table-column
          :formatter="formatDate"
          align="center"
          label="分配日期"
          prop="allocationDate"></el-table-column>

      <el-table-column align="center" label="退宿日期" prop="checkOutDate2">
        <template slot-scope="scope">
          {{ scope.row.checkOutDate2 || '/' }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="备注" prop="remark"></el-table-column>
      <el-table-column align="center" label="宿舍状态" prop="status"></el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <!--          <el-link style="margin-left: 10px;" type="success" @click="handleEdit(scope.row)"> 查看 </el-link>-->
          <!--        <el-link style="margin-left: 10px;" type="primary" @click="showUpdateDormitoriesModal(scope.row.assignmentId)"> 编辑 </el-link>-->
          <el-link style="margin-left: 10px;" type="danger" @click="confirmDelete(scope.row.assignmentId)"> 删除
          </el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加分页器 -->
    <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"></el-pagination>


  </div>
</template>

<script>
// import UpdateDormitoryAllocation from "@/components/dormitoryAllocation/UpdateDormitoryAllocation.vue";
import AddDormitoryAllocation from "@/components/dormitoryAllocation/AddDormitoryAllocation.vue";

export default {
  components: {
    AddDormitoryAllocation,
    // UpdateDormitoryAllocation
  },
  data() {
    return {
      dormitoryAllocationList: [], //宿舍用户关系表
      dormitoryTypeMap: {
        0: '女生宿舍',
        1: '男生宿舍',
        2: '混合宿舍'
      },
      buildingName: [],//楼栋集合
      unitCode: [],//单元集合
      roomNumber: [],//房间号计划
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 条件查询的数据
      searchForm: {
        buildingId: '',//楼栋名称
        dormitoryType: '',//宿舍类型
        unitId: '',//单元名称
        floor: '',//楼层
        dormitoryId: "",//房间号
        dormitoryBed: '',//床位数
        assigned: '',//已分配
        name: '',//学生姓名
        checkOutOrNot: '',//是否退宿
        status: ''//宿舍状态
      },
      message: '',
      isUpdateDormitoryAllocationVisible: false,
      isAddDormitoryAllocationVisible: false,
    }
  },
  watch: {
    // 监听 message 属性的变化
    message(newValue, oldValue) {
      this.getDormitoriesById(newValue);
    },
    // 监听 searchForm.buildingId 属性的变化
    'searchForm.buildingId': function (newBuildingId, oldBuildingId) {
      // 执行您的逻辑代码
      console.log('buildingId 的值发生变化:', newBuildingId);
      this.searchForm.unitId = "";
      this.queryUnitInformation();
    },
    // 监听 searchForm.unitId 属性的变化
    'searchForm.unitId': function (newUnitId, oldUnitId) {
      // 执行您的逻辑代码
      console.log('unitId 的值发生变化:', newUnitId);
      this.searchForm.dormitoryId = "";
      this.queryRoomNumber();
    }

  },
  created() {
    this.fetchData();
    // 查询楼栋信息
    this.queryBuildingInformation();
    //   查询单元信息
    this.queryUnitInformation()
    //   查询房间号
    this.queryRoomNumber()
  },
  methods: {
    // 成功提示信息
    succeed(msg) {
      this.$message({
        message: msg,
        type: 'success'
      });
    },
    hideDialog() {
      this.isAddDormitoryAllocationVisible = false;
      this.isUpdateDormitoryAllocationVisible = false;
      // 调用搜索方法，重新加载数据
      this.fetchData();
    },
    showAddUnitModal() {
      this.isAddDormitoryAllocationVisible = true;
    },
    handleAddDormitoryAllocation() {
      // 处理添加单元信息成功后的逻辑
      // 关闭模态框等操作
      this.isAddDormitoryAllocationVisible = false;
    },
    handleUpdateDormitoryAllocation() {
      // 处理添加楼栋信息成功后的逻辑
      // 关闭模态框等操作
      this.isUpdateDormitoryAllocationVisible = false;
    },

    handleSizeChange(size) {
      // 每页条数变更
      this.pageSize = size;
      this.fetchData();
    },
    handleCurrentChange(page) {
      // 当前页码变更
      this.currentPage = page;
      this.fetchData();
    },
    // 查询楼栋信息
    queryBuildingInformation() {
      // 调用后端接口获取数据
      this.$axios.post('/api/buildings/list', {}, {headers: {'token': this.$store.getters.getToken}}).then(response => {
        // 请求成功后更新表格数据和分页信息
        if (response.data.code === 200) {
          // 使用 reduce 构建以 userId 为键，name 为值的对象
          this.buildingName = response.data.data.reduce((arr, user) => {
            // 将当前用户的 userId 作为键，name 作为值，添加到累积的数组中
            arr.push({value: user.buildingId, label: user.buildingName});
            return arr;
          }, []);
        } else {
          this.$message.error(response.data.msg || '查询楼栋信息失败');
        }
      }).catch(error => {
        this.$message.error(error || '查询楼栋信息失败');
      });
    },
    // 查询单元信息
    queryUnitInformation() {
      this.unitCode = [];
      // 调用后端接口获取数据
      this.$axios.post('/api/units/list', {
        buildingId: this.searchForm.buildingId
      }, {headers: {'token': this.$store.getters.getToken}}).then(response => {
        // 请求成功后更新表格数据和分页信息
        if (response.data.code === 200) {

          if (response.data.data.length > 0) {
            this.unitCode = response.data.data.reduce((arr, unit) => {
              // 将当前用户的 userId 作为键，name 作为值，添加到累积的数组中
              arr.push({value: unit.unitId, label: unit.unitCode});
              return arr;
            }, []);
          }
        } else {
          this.$message.error(response.data.msg || '查询单元信息失败');
        }
      }).catch(error => {
        // 错误处理
        this.$message.error(error || '查询单元信息失败');
      });
    },
    // 根据单元查询房间号
    queryRoomNumber() {
      this.roomNumber = [];
      this.$axios.post('/api/dormitories/list', {
        unitId: this.searchForm.unitId
      }, {headers: {'token': this.$store.getters.getToken}}).then(response => {
        // 请求成功后更新表格数据和分页信息
        if (response.data.code === 200) {
          if (response.data.data.length > 0) {
            this.roomNumber = response.data.data.reduce((arr, dormitory) => {
              // 将当前用户的 userId 作为键，name 作为值，添加到累积的数组中
              arr.push({value: dormitory.dormitoryId, label: dormitory.roomNumber});
              return arr;
            }, []);
          }
        } else {
          this.$message.error(response.data.msg || '查询房间号失败');
        }
      }).catch(error => {
        // 错误处理
        this.$message.error(error || '查询房间号失败');
      });
    },
    // 查询学生宿舍关系表(多表查询)
    fetchData() {
      // 调用后端接口获取数据
      this.$axios.post('/api/studentDormAssignments/getStudentDormAssignmentsPage?pageNum=' + this.currentPage + '&pageSize=' + this.pageSize, {
        buildingId: this.searchForm.buildingId,
        dormitoryType: this.searchForm.dormitoryType,
        unitId: this.searchForm.unitId,
        floor: this.searchForm.floor,
        dormitoryId: this.searchForm.dormitoryId,
        dormitoryBed: this.searchForm.dormitoryBed,
        name: this.searchForm.name,
        checkOutOrNot: this.searchForm.checkOutOrNot,
        status: this.searchForm.status
      }, {headers: {'token': this.$store.getters.getToken}}).then(response => {
        // 请求成功后更新表格数据和分页信息
        if (response.data.code === 200) {
          this.dormitoryAllocationList = response.data.data.list;
          this.total = response.data.data.total;
          this.succeed("查询成功");
        } else {
          this.$message.error(response.data.msg || '查询学生宿舍关系表失败');
        }
      }).catch(error => {
        // 错误处理
        this.$message.error(error || '查询学生宿舍关系表失败');
      });
    },
    // 提示是否删除
    confirmDelete(assignmentId) {
      // 弹出确认提示框
      this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户点击确定按钮后执行删除操作
        this.deleteDormitoryAllocation(assignmentId);
      }).catch(() => {
        // 用户点击取消按钮，不执行任何操作
      });
    },
    deleteDormitoryAllocation(assignmentId) {
      // 发送DELETE请求
      this.$axios.delete(`/api/studentDormAssignments/delete/${assignmentId}`)
          .then(response => {
            if (response.data.code === 200) {
              // 请求成功，处理响应
              this.succeed("删除成功");
              // 在这里可以根据需要执行一些操作，比如更新界面等
              this.fetchData();
            } else {
              this.$message.error(response.data.msg || '删除信息失败');
            }
          })
          .catch(error => {
            // 请求失败，处理错误
            this.$message.error(error || '删除信息失败');
          });
    },
    showUpdateDormitoriesModal(assignmentId) {
      this.message = assignmentId;
      this.isUpdateDormitoryAllocationVisible = true;
    },
    // 清除搜索条件
    handleReset() {
      // 清空搜索条件对象
      this.searchForm.buildingId = '';//楼栋名称
      this.searchForm.dormitoryType = '';//宿舍类型
      this.searchForm.unitId = '';//单元名称
      this.searchForm.floor = '';//楼层
      this.searchForm.dormitoryId = '';//房间号
      this.searchForm.dormitoryBed = '';//床位数
      this.searchForm.status = '';//宿舍状态
      this.searchForm.checkOutOrNot = '';//是否退宿
      this.searchForm.name = ''//学生姓名
      // 调用搜索方法，重新加载数据
      this.fetchData();
    },
    formatDate(row, column) {
      const date = row.allocationDate;  // 假设这是时间属性名
      if (date) {
        return this.formatDateOnly(date);  // 假设 formatDateOnly 是你自定义的时间格式化函数
      } else {
        return '';  // 如果时间为空，返回空字符串或者其他适当值
      }
    },
    formatDateOnly(date) {
      const d = new Date(date);
      const year = d.getFullYear();
      const month = this.padZero(d.getMonth() + 1);
      const day = this.padZero(d.getDate());
      return `${year}年${month}月${day}日`;
    },
    padZero(value) {
      return value < 10 ? '0' + value : value.toString();
    }
  }

}


</script>


<style scoped>

</style>
